package slidingpenguins.utils {
	import flash.events.Event;
	import flash.events.EventDispatcher;

	import mx.collections.IList;
	import mx.events.CollectionEvent;

	public class ListTypeRestricter extends EventDispatcher implements IList {
		private var list:IList;
		private var type:Class;

		private function handleCollectionChange(event:CollectionEvent):void {
			dispatchEvent(event);
		}

		public function ListTypeRestricter(list:IList, type:Class) {
			this.list = list;
			this.type = type;

			list.addEventListener(CollectionEvent.COLLECTION_CHANGE, handleCollectionChange);
		}

		public function get length():int {
			return list.length;
		}

		public function addItem(item:Object):void {
			if (!(item is type)) {
				throw new ArgumentError();
			}

			list.addItem(item);
		}

		public function addItemAt(item:Object, index:int):void {
			if (!(item is type)) {
				throw new ArgumentError();
			}

			list.addItemAt(item, index);
		}

		public function getItemAt(index:int, prefetch:int = 0):Object {
			return list.getItemAt(index, prefetch);
		}

		public function getItemIndex(item:Object):int {
			return list.getItemIndex(item);
		}

		public function itemUpdated(item:Object, property:Object = null, oldValue:Object = null, newValue:Object = null):void {
			if (!(newValue is type)) {
				throw new ArgumentError();
			}

			list.itemUpdated(item, property, oldValue, newValue);
		}

		public function removeAll():void {
			list.removeAll();
		}

		public function removeItemAt(index:int):Object {
			return list.removeItemAt(index);
		}

		public function setItemAt(item:Object, index:int):Object {
			if (!(item is type)) {
				throw new ArgumentError();
			}

			return list.setItemAt(item, index);
		}

		public function toArray():Array {
			return list.toArray();
		}
	}
}
